<?php
/**
 * Created by PhpStorm.
 * User: 65736
 * Date: 2019/3/13 0013
 * Time: 12:59
 */

namespace app\common\widget;


class WidgetCheckBox extends WidgetInput
{
    /**
     * CheckBox 列表数组 [数组key为CheckBox的value] [数组value为CheckBox的显示名称]
     * @var array
     */
    private $checkBoxList = [];

    /**
     * CheckBox input Html
     * @var array
     */
    private $checkBoxInputList = [];

    /**
     * 构造方法, 渲染挂件
     * @return mixed
     * @throws \think\Exception
     */
    function render()
    {
        // 创建表单数据
        $this->createCheckBoxInput();
        // 分配数据
        self::$view->assign('checkBoxInputList', $this->checkBoxInputList);

        return $this->fetch();
    }

    /**
     * Create Input Html list
     * @return $this
     * @throws \think\Exception
     * @throws \Exception
     */
    private function createCheckBoxInput() {
        // check data
        if ( !$this->checkBoxList ) $this->throwException("CheckBox挂件数据为空");
        // 获取id和name
        $id = $this->getId();
        $name = $this->getName();
        $domAttrs = $this->domAttrs;
        // Create data
        foreach ( $this->checkBoxList as $key=>$value ) {
            if ( !$id )  {
                $_id = "checkbox_{$name}_{$key}";
            }else{
                $_id = "checkbox_{$name}_{$id}";
            }
            // 表单对象
            $input = new WidgetInput();
            // 设置表单对象
            $input->setDomAttrList($domAttrs)
                ->setInputType(parent::inputTypeCheckBox)
                ->setClass( $this->getClass() )
                ->remClass( self::defaultClass )
                ->setValue( $key )
                ->setId($_id);
            if ( $name )  $input->setName( $name );

            // 设置选中
            $_value = $this->getValue();
            if ( ''!==$_value && ( ( is_array( $_value ) && in_array($key,$_value ) )||($key == $_value) ) ) {
                $input->setDomAttr("checked", "checked");
            }

            // 生成数据
            $html = $input->render();
            $html .= $value;
            $html = "<div class='checkbox'><label>{$html}</label></div>";
            $this->checkBoxInputList[] = $html;
        }
        return $this;
    }

    /**
     * Set CheckBox List
     * @param array $checkBoxList
     * @return $this
     * @throws \think\Exception
     */
    public function setCheckBoxList( array $checkBoxList ) {
        if ( !$checkBoxList ) $this->throwException("CheckBox列表错误");
        $this->checkBoxList = $checkBoxList;
        return $this;
    }

    /**
     * Get CheckBox Input List
     * @return array
     */
    public function getCheckBoxInputList(): array
    {
        return $this->checkBoxInputList;
    }

    /**
     * Get CheckBox List
     * @return array
     */
    public function getCheckBoxList(): array
    {
        return $this->checkBoxList;
    }




}